package cn.edu.seu.ssny.service.impl;

import cn.edu.seu.ssny.common.utils.MD5Utils;
import cn.edu.seu.ssny.dao.IUserDao;
import cn.edu.seu.ssny.dao.support.IBaseDao;
import cn.edu.seu.ssny.entity.*;
import cn.edu.seu.ssny.service.IProjectService;
import cn.edu.seu.ssny.service.IRoleService;
import cn.edu.seu.ssny.service.IUserService;
import cn.edu.seu.ssny.service.support.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;

/**
 * 用户账户表
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User, Integer> implements IUserService {

    @Autowired
    private IUserDao userDao;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IProjectService projectService;

    @Override
    public IBaseDao<User, Integer> getBaseDao() {
        return this.userDao;
    }

    @Override
    public User findByUserName(String username) {
        return userDao.findByUserName(username);
    }

    @Override
    public void saveOrUpdate(User user) {
        if (user.getId() != null) {
            update(user);
        } else {
            user.setPassword(MD5Utils.md5(user.getPlaintextPassword()));
            save(user);
        }
    }

    @Override
    public void register(User user, Enterprise enterprise) {
        user.setPassword(MD5Utils.md5(user.getPlaintextPassword()));
        user.setEnterprise(enterprise);
        save(user);
    }


    @Override
    public void delete(Integer id) {
        User user = find(id);
//		Assert.state(!"admin".equals(user.getUserName()),"超级管理员用户不能删除");
        super.delete(id);
    }

    /**
     * 给用户分配项目
     *
     * @param id         用户ID
     * @param projectIds 项目Id
     */
    @Override
    public void grant(Integer id, String[] projectIds) {
        User user = find(id);
        if (user.getRole().getLevel() == IRoleService.SUPER_LEVEL)
            return;
        Project project;
        List<Project> projects = new ArrayList<Project>();
        if (projectIds != null) {
            for (int i = 0; i < projectIds.length; i++) {
                if (StringUtils.isBlank(projectIds[i]) || "0".equals(projectIds[i])) {
                    continue;
                }
                Integer rid = Integer.parseInt(projectIds[i]);
                project = projectService.find(rid);
                projects.add(project);
            }
        }
        user.setProjects(projects);
        update(user);
    }

}
